/**
 * 
 */
package com.lanswon.qzsmk.listener;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.model.ActiveUser;

/**
 * shiro登陆认证
 * @author sun
 *
 */
@Component
public class LoginSuccessFilter extends FormAuthenticationFilter {

	private static Logger logger = (Logger) LoggerFactory.getLogger(LoginSuccessFilter.class);

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		HttpServletRequest httpReq = (HttpServletRequest) request;
		logger.debug("########login success#########");
		ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
		// httpReq.getSession().setAttribute("activeUser", activeUser);
		subject.getSession().setAttribute("activeUser", activeUser);
		WebUtils.getAndClearSavedRequest(request);
		WebUtils.redirectToSavedRequest(request, response, "/index.html");
		return false;
	}

	// 表示当访问拒绝时是否已经处理了；如果返回true表示需要继续处理；
	//如果返回false表示该拦截器实例已经处理了，将直接返回即可
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		logger.debug("########login validCode#########");

		// 校验验证码
		// 从session获取正确的验证码
		HttpSession session = ((HttpServletRequest) request).getSession();
		// 页面输入的验证码
		String randomcode = request.getParameter("validCode");
		// 从session中取出验证码
		String validateCode = (String) session.getAttribute("VALID_CODE");
		if (randomcode != null && validateCode != null && !randomcode.equalsIgnoreCase(validateCode)) {
			// randomCodeError表示验证码错误
			logger.debug("输入{},生成{},相等吗？{}", randomcode, validateCode, randomcode.equalsIgnoreCase(validateCode));
			request.setAttribute("shiroLoginFailure", "randomCodeError");
			// 拒绝访问，不再校验账号和密码
			return true;
		}

		HttpServletResponse res = WebUtils.toHttp(response);

			if (isAjax(WebUtils.toHttp(request))) {
				 res = WebUtils.toHttp(response);
//				 res.setHeader("session-status", "timeout");//在响应头设置session状态
//					logger.debug("设置:status");	
				 res.setStatus(403);
				String path= request.getServletContext().getContextPath();
				 logger.debug("path==={}",path);
				 res.getWriter().write(path);
					return true;

		}
		
		

		return super.onAccessDenied(request, response, mappedValue);
	}

	public static boolean isAjax(ServletRequest request) {
		String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
		if ("XMLHttpRequest".equalsIgnoreCase(header)) {
			System.out.println("当前请求为Ajax请求");
			return Boolean.TRUE;
		}
		System.out.println("当前请求非Ajax请求");
		return Boolean.FALSE;
	}

}
